package cn.maidouya.user.intercepter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 *      登录拦截器
 */
@Component
public class LoginIntercepter implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 每次点击获取token是否有权限，没有就被拦截，  有就放行并且重新绑定设置时间
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)){// 放行
            Object loginObj = redisTemplate.opsForValue().get(token);
            if (loginObj != null){
                redisTemplate.opsForValue().set(token,loginObj,30, TimeUnit.MINUTES);
                return true;
            }
        }
        // 不放行，重定向到登录页面  必须使用标准的json格式
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writerLogin = response.getWriter();

        writerLogin.write("{\"success\":false, \"message\":\"noLogin\"}");
        writerLogin.flush();
        writerLogin.close();
        return false;
    }
}